﻿using System;
using System.Xml.Serialization;
using Microsoft.WindowsAzure.StorageClient;

namespace CloudMailShared
{
    public class CloudMailClient
    {
        private XmlSerializer mailMessageSerializer = new XmlSerializer(typeof(SerializableMailMessage));
        private MailCloudStorage mailCloudStorage = null;


        /// <summary>
        /// Initializes a new instance of the <see cref="CloudMailClient"/> class 
        /// for use with the Azure Development Fabric only.
        /// </summary>
        /// <param name="mailQueueName">Name of the mail queue.</param>
        public CloudMailClient(string mailQueueName)
        {
            mailCloudStorage = new MailCloudStorage(mailQueueName);
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="CloudMailClient"/> class.
        /// </summary>
        /// <param name="azureStorageUrl">The azure storage URL.</param>
        /// <param name="mailQueueName">Name of the mail queue.</param>
        public CloudMailClient(string mailQueueName, string azureStorageUrl)
        {
            mailCloudStorage = new MailCloudStorage(azureStorageUrl, mailQueueName);
        }

        /// <summary>
        /// Sends the mail message to cloud storage.
        /// </summary>
        /// <param name="mailMessage">The mail message.</param>
        public void sendMessage(SerializableMailMessage mailMessage)
        {  
            string msgName = Guid.NewGuid().ToString();
            CloudBlob blob = mailCloudStorage.MailStorageContainer.GetBlobReference(msgName);

            using (BlobStream blobstream = blob.OpenWrite())
            {
                mailMessageSerializer.Serialize(blobstream, mailMessage);
                blobstream.Close();
            }

            mailCloudStorage.MailQueue.AddMessage(new CloudQueueMessage(msgName));
        }
    }
}


